<?php

namespace App\Models;

use AlibabaCloud\Tea\Utils\Utils;
use http\Env;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;

class Sms extends Model
{
    use SoftDeletes;
    protected $table = 'sms';
    protected static $expired = '600'; //10分钟

    /**
     * 定义主键
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 禁止批量赋值的字段
     *
     * @var array
     */
    protected $guarded = ['id','created_at','deleted_at'];

    /**
     * 软删除应该被调整为日期的属性
     * [$dates description]
     * @var [type]
     */
    protected $dates=[
        'created_at', 'updated_at','deleted_at'
    ];


    //更改时间格式
    public function getCreatedAtAttribute($created_at){
        return strtotime($created_at);
    }


    public static function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = config('sms.domain');
        return new Dysmsapi($config);
    }


    //发送验证码
    public static function send($mobile,$templateParam){
        $client = self::createClient(config('sms.access_key_id'),config('sms.access_key_secret'));
        //1、发送短信
        $sendReq = new SendSmsRequest([
            'phoneNumbers'         => $mobile,
            'signName'             => '瑞呈物联',
            'templateCode'         => 'SMS_171353465',
            'templateParam'        => $templateParam,
        ]);
        $sendResq = $client -> sendSms($sendReq);
        $code = $sendResq->body->code;
        if (!Utils::equalString($code, "OK")) {
            //return $sendResp->body->message;
            return false;
        }

        //$bizId = $sendResp->body->bizId;
        //return $bizId;
        return true;
    }

    // 短信验证
    public static function check($code,$mobile,$event){
        $res = self::where('mobile',$mobile) -> where('event',$event) -> where('status', 0) -> orderBy('id', 'desc') -> first();

        if($res){
            if($res -> created_at > (time() - (self::$expired)) && $res -> code == $code){
                $res -> status = 1;
                $re = $res -> save();
                return true;
            }
        }
        return false;
    }

    // 存储短信
    public static function store($mobile,$event){

        $test_num = [
            '18536499304', // 张晓男
            '13834632919', // 段瑞
            '18303412455',
            ];

        // 测试号不发送短信 默认为 1111
        if (in_array($mobile, $test_num)) {
            $code = 1111;
            $sms = self::create(['mobile' => $mobile, 'event' => $event, 'ip' => request() -> ip(), 'code' => $code]);
            return true;
        } else {

            // 十分钟内 不超过5条短信
            $count5 = self::where('mobile',$mobile) -> where('event',$event)
                -> whereRaw('UNIX_TIMESTAMP(created_at) >'.(time() - 600))
                -> where('status',0)
                -> count();

            if($count5 >= 5 ){
                return ['error' => 4016];
            }else{
                $code = random_int(1000,9999);
                $templateParam = json_encode(['code' => $code]);
                if($res = self::send($mobile, $templateParam)){
                    $sms = self::create(['mobile' => $mobile, 'event' => $event, 'ip' => request() -> ip(), 'code' => $code]);
                    return true;
                }else{
                    return false;
                }
            }

        }




    }
}
